package l1j.opqlo.Timer.Controler;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.opqlo.Server.L1World.WorldItem;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_SystemMessage;

public class ItemTimeDelete extends TimerTask {

	private static Logger _log = Logger.getLogger(ItemTimeDelete.class
			.getName());
	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
			final Collection<L1ItemInstance> all = WorldItem.get().all();
			// 不包含元素
			if (all.isEmpty()) {
				return;
			}
			for (final L1ItemInstance item : all) {
				final Timestamp deleteDate = item.getDeleteDate();
				if (deleteDate == null) {
					continue;
				}
				final Calendar cal = Calendar.getInstance();
				final long checkDeleteDate = (cal.getTimeInMillis() - deleteDate.getTime()) / 1000;
				if (checkDeleteDate >= 0) {
					final Collection<L1PcInstance> allpc = L1World.getInstance().getAllPlayers();
					if (!allpc.isEmpty()) {
						for (final L1PcInstance pc : allpc) {
							if (pc.getInventory().getItem(item.getId()) != null) {
								pc.getInventory().removeItem(item);
								pc.sendPackets(new S_SystemMessage("\\aE"+ item.getLogName() + " 時間到期，已被系統回收。"));
								break;
							}
						}
					}
					// L1World.getInstance().removeObject(item);
				}
				Thread.sleep(1);
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final ItemTimeDelete partyTimer = new ItemTimeDelete();
			partyTimer.start();
		}
	}

	public void start() {
		final int timeMillis = 1000;// 10秒
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,
				timeMillis, timeMillis);
	}
}